<script setup>
import { ref , onMounted } from 'vue'
import Map from 'ol/Map'
import View from 'ol/View'
import Style from "ol/style/Style";
import { Fill, Stroke,Text } from "ol/style";
import VectorImageLayer from "ol/layer/VectorImage";
import VectorSource from "ol/source/Vector";
import VectorLayer from "ol/layer/Vector";
import GeoJSON from "ol/format/GeoJSON";

const map = ref(null)
const info = ref(null)
const featureOverlay = ref(null)
let highlight = null;
const styles = new Style({
  fill: new Fill({
    color: 'rgba(255, 255, 255, 0.6)',
  }),
  stroke: new Stroke({
    color: '#319FD3',
    width: 1,
  }),
  text: new Text({
    fill: new Fill({
      color: '#008c8c',
    }),
  }),
})

const displayFeatureInfo = (pixel) => {
  // 获取图层 , 根据像素位置获取feature
  // feature 代表图形实体，包括几何形状、属性、样式等信息 以及geom geom代表几何信息
  map.value.getLayers().item(0).getFeatures(pixel).then(features => {
    // console.log(features,'features')
    const feature = features.length > 0 ? features[0] : undefined;

    if (feature) {
      //获取到的要素的名称渲染到，屏幕左上角
      info.value.innerHTML = feature.get('name');
    } else {
      info.value.innerHTML = '&nbsp;';
    }

    if (feature !== highlight){
      if (highlight) {
        featureOverlay.value.getSource().removeFeature(highlight);
      }
      if (feature) {
        featureOverlay.value.getSource().addFeature(feature);
      }
      highlight = feature;
    }
  })
}

const initMap = () => {
  map.value = new Map({
    target: 'map',//指定挂载dom，注意必须是id
    layers: [
      // 加载矢量影像图层
      new VectorImageLayer({
        imageRatio: 2,
        source: new VectorSource({
          url: 'https://geo.datav.aliyun.com/areas_v2/bound/100000_full.json',
          format: new GeoJSON(),//指定数据读取格式
        }),
        style: function (feature){
          // 设置文字内容
          styles.getText().setText(feature.get('name'));
          return styles;
        }
      })
    ],
    //配置视图
    view: new View({
      center: [113.24981689453125, 23.126468438108688], //视图中心位置
      projection: "EPSG:4326", //指定投影
      zoom: 4   //缩放到的级别
    })
  })
  featureOverlay.value = new VectorLayer({
    source: new VectorSource(),
    style: new Style({
      stroke: new Stroke({
        color: '#f00',
        width: 1,
      }),
      fill: new Fill({
        color: 'rgba(255,0,0,0.1)',
      }),
    }),
    map: map.value,
  })

  map.value.on('pointermove',evt=>{
    if (!evt.dragging){
      // 相对于与原始事件对应的视口的贴图像素。
      displayFeatureInfo(evt.pixel);
    }
  })

  map.value.on('click',evt=>{
      // 相对于与原始事件对应的视口的贴图像素。
      displayFeatureInfo(evt.pixel);
  })

}

onMounted(initMap)
</script>

<template>
  <!--地图挂载dom-->
  <div id="map">
    <div id="info" ref="info">&nbsp;</div>
  </div>
</template>

<style scoped>
#map{
  width: 100%;
  height: 100%;
}
</style>